
Ext.ns('X.store');

//------------------------//
//       Json Store       //
//------------------------//

X.store.Json = Ext.extend(Ext.data.JsonStore, {

    constructor: function(config)
    {
        config.totalProperty = 'total';
        config.root          = 'rows';
        config.remoteSort    = true;
        config.baseParams    = {start:0, limit:20};
        config.listeners =
        {
            load       : function(){this.setSubmitField();},
            add        : function(){this.setSubmitField();},
            remove     : function(){this.setSubmitField();},
            update     : function(){this.setSubmitField();},
            datachanged: function(){this.setSubmitField();},
            exception  : function(proxy, type, action, o, response, args){
                try{
                    if (type=='response'){
                        X.msg.Failure('respuesta inválida del servidor');
                    }
                    if (type=='remote'){
                        X.msg.Failure(response.raw.msg);
                    }
                }
                catch(e){
                    X.msg.FailureJs(e.message);
                }
            }
        };

        // super class constructor
        X.store.Json.superclass.constructor.call(this, config);
    },

    setSubmitField : function(){
        try{
            // guardar los records actuales en el X.field
            // con el id=this.submitFieldId (especificado por el owner GridPanel)
            if (           this.submitFieldId )
            if (Ext.getCmp(this.submitFieldId)){
                Ext.getCmp(this.submitFieldId).setValue( this.getJson() );
            }
        }
        catch(e){
            X.msg.FailureJs(e.message);
        }
    },

    // set Json data
    setJson : function(jsontext)
    {
        this.loadData(JSON.parse(jsontext));
    },
    
    // get Json data
    getJson : function()
    {
        // obtener los nombres de las columnas
        var cols = new Array();
        this.fields.each(function(item, index, length){
            cols.push(item.name);
        });

        var rows = new Array();
        for (var r=0; r<this.getCount(); r++){
            // para cada fila
            var cels = new Array();
            var record = this.getAt(r);

            for (var c=0; c<cols.length; c++){
                var val;
                try{
                    val = Date.parseDate(record.get(cols[c]), 'Y-m-d').format('d/m/Y');
                }catch(e){ try{
                    val = Date.parseDate(record.get(cols[c]), 'Y-m-d H:i:s').format('d/m/Y');
                }catch(e){ try{
                    val = record.get(cols[c]).format('d/m/Y');
                }catch(e){
                    val = record.get(cols[c]);
                }}}
        
                if (typeof val == 'string'){
                    val = val.replace(/"/g,'\\"');
                }

                // para cada columna de la fila
                cels.push( '"' + cols[c] + '":' + ( val ? '"'+val+'"' : 'null' ) );
            }
            rows.push('{'+cels.join(',')+'}');
        }

        return '['+rows.join(',')+']';
    }
});